<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>百度联想词</title>
</head>
<body>
  <div class="search-wrap">
    <div class="input-wrap">
      <input type="text" class="search-input J_searchInput">
    </div>
    <div class="list-wrap">
      <ul class="wd-list J_wdList">
        
      </ul>
    </div>
  </div>
  <script type="text/html" id="J_listTpl">
    <li class="wd-item">
      <a href="https://www.baidu.com/s?wd={{wdLink}}" target="_blank" class="wd-lk">{{wd}}</a>
    </li>
  </script>
  
</body>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script>
;(function(doc){
  var searchInput = doc.getElementsByClassName("J_searchInput")[0],
      wdList = doc.getElementsByClassName('J_wdList')[0],
      listWrap = wdList.parentNode,
      listTpl = doc.getElementById('J_listTpl').innerHTML;

  var init = function(){
    bindEvent();
  }

  var bindEvent = function(){
    searchInput.addEventListener('input', typeInput, false);
  }

  function renderList(data){
    var list = '',
        data = data.g,
        len = data.length,
        val = _trimSpace(searchInput.value);
    
    if(len){
      data.forEach(function(elem){
        list += listTpl.replace(/{{(.*?)}}/g, function(node, key){
          return {
            wdLink: elem,
            wd:  elem,
          }[key].q;
        });
      });
      wdList.innerHTML = list;
      listWrap.style.display = 'block';
    }else{
      wdList.innerHTML = '';
      listWrap.style.display = 'none';
    }
  }

  function typeInput(){
    var val = _trimSpace(this.value),
        len = val.length;
    
    if(len > 0){
      getDatas(val, 'setDatas');
    }else{

    }
  }

  function getDatas(value, callbackName){
    var oScript = doc.createElement('script');
    oScript.src = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=31253,26350&wd='+ value + '&cb=' + callbackName;
    doc.body.appendChild(oScript);
    doc.body.removeChild(oScript);
  }

  function _trimSpace(str){
    return str.replace(/\s+/g, '');
  }

  // function _setWdStyle(value, word){
  //   return '<span class="font-normal">' + value + '</span>' + word.replace(value, '')
  // }

  window.setDatas = function(data){
    console.log(data);
    renderList(data);
  }

  //https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=31253,26350&wd=%E4%BA%AC%E4%B8%9C&bs=%E4%BA%AC%E4%B8%9C&csor=2&cb=jQuery110207251303117703372_1630511994402&_=1630511994403

  init();
})(document)
</script>
</html>